package cn.gs.timer.server;

import cn.gs.common.interfaces.ITimerListener;
import cn.gs.common.interfaces.ITimerServer;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.text.MessageFormat;
import java.util.logging.Level;
import java.util.logging.Logger;

/*
 * @author gs
 */
public class TimerServer extends UnicastRemoteObject implements ITimerServer {

    public TimerServer() throws RemoteException {
    }

    public boolean init(String serverName) {
        try {
//            LocateRegistry.createRegistry(Main.common.getServerConfig().getPort());
            String uri = MessageFormat.format("//{0}:{1}/TimerServer", Main.common.getServerConfig().getIp(), String.valueOf(Main.common.getServerConfig().getPort()));
            Naming.rebind(uri, this);
            Logger.getLogger(this.getClass().getName()).log(Level.INFO, serverName + " timer Started Successed. " + uri);
        } catch (RemoteException | MalformedURLException ex) {
            Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, serverName + " Start Failed by Server Exception.", ex);
            return false;
        }
        return true;
    }

    @Override
    public int getNow() throws RemoteException {
        return Main.timerThread.setting.getNow();
    }

    @Override
    public void registerServer(String server, String addr) throws RemoteException {
        try {
            ITimerListener listener = (ITimerListener) Naming.lookup(addr);
            Main.timerThread.registerServer(server, listener);
            Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Success to add new server " + server + "#" + addr);
        } catch (NotBoundException | MalformedURLException ex) {
            Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
            throw new RemoteException("Fail to add this server: " + server + "#" + addr, ex);
        }
    }

    @Override
    public void removeServer(String server) throws RemoteException {
        Main.timerThread.removeServer(server);
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Success to remove server: " + server);
    }
}
